/**
 * Created by XianTao on 2016/12/1
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.biz.wechat.nmgat.mobile.api.restful;

import org.lego.jpa.base.vo.ResultVo;
import org.lego.util.ApiResult;
import org.lego.util.HttpUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/thirdPart")
public class ThirdPartRestful {
    private String nmgatWebsiteBaseUrl = "http://xxx.tunnel.qydev.com/trsRest";

    /**
     * 内蒙古公安厅网站接口的加密算法
     */
    private static String encryptForNmgat(String requestString) {
        FileInputStream f = null;
        ObjectInputStream b = null;
        try {
            // 获取公钥及参数e,n
            f = new FileInputStream("G:\\legocode\\LegoBoot\\BizWechatNmgatMobileApi\\src\\main\\resources\\nmgatKey\\pubkey.dat");
            b = new ObjectInputStream(f);
            RSAPublicKey pbk = (RSAPublicKey) b.readObject();
            BigInteger e = pbk.getPublicExponent();
            BigInteger n = pbk.getModulus();
            // 获取明文m
            byte ptext[] = requestString.getBytes("UTF-8");
            BigInteger m = new BigInteger(ptext);
            // 计算密文c
            BigInteger c = m.modPow(e, n);
            // 密文
            return c.toString();
        } catch (Exception e) {
            return requestString;
        } finally {
            if (!ObjectUtils.isEmpty(b)) {
                try {
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (!ObjectUtils.isEmpty(f)) {
                try {
                    f.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 内蒙古公安厅网站接口的时间戳
     */
    private static String getRequestTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

    @RequestMapping(value = "/nmgat/webChannels", method = RequestMethod.POST)
    public ResultVo<List> getAllChannel() {
        String json = HttpUtil.get(nmgatWebsiteBaseUrl + "/getAllChannel");
        ApiResult apiResult = ApiResult.create(json);
        if (!apiResult.isSucceed("errCode")) {
            throw new InvalidParameterException(apiResult.getStr("errMsg"));
        }
        return new ResultVo<List>(apiResult.getList("channels"));
    }

    @RequestMapping(value = "/nmgat/docList/{channelId}", method = RequestMethod.POST)
    public ResultVo<List> getDocListByChannelId(@PathVariable(value = "channelId") String channelId) {
        String json = HttpUtil.get(nmgatWebsiteBaseUrl + "/getByChannelId/" + encryptForNmgat(channelId + "/1/2/" + getRequestTime()));
        ApiResult apiResult = ApiResult.create(json);
        if (!apiResult.isSucceed("errCode")) {
            throw new InvalidParameterException(apiResult.getStr("errMsg"));
        }
        return new ResultVo<List>(apiResult.getList("documents"), apiResult.getInt("itemTotal"));
    }

    @RequestMapping(value = "/nmgat/docDetail/{docId}", method = RequestMethod.POST)
    public ResultVo<Map> getDocDetailByDocId(@PathVariable(value = "docId") String docId) {
        String json = HttpUtil.get(nmgatWebsiteBaseUrl + "/detail/" + encryptForNmgat(docId + "/" + getRequestTime()));
        ApiResult apiResult = ApiResult.create(json);
        if (!apiResult.isSucceed("errCode")) {
            throw new InvalidParameterException(apiResult.getStr("errMsg"));
        }
        return new ResultVo<Map>(apiResult.getMap("document"));
    }
}
